package com.poly.police.monitor.admin.config.stp;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.poly.police.monitor.application.config.UserThreadLocal;
import com.poly.police.monitor.application.mapper.sys.SysMenuMapper;
import com.poly.police.monitor.application.mapper.sys.SysPermMapper;
import com.poly.police.monitor.common.util.StringUtils;
import com.poly.police.monitor.pojo.entity.sys.SysMenu;
import com.poly.police.monitor.pojo.entity.sys.SysPerm;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Sa-Token自定义权限验证接口
 */
@Component
public class StpInterConfig implements StpInterface {

    @Resource
    SysPermMapper sysPermMapper;

    @Resource
    SysMenuMapper sysMenuMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     *
     * @param loginId 登录ID
     * @param loginType 登录类型
     * @return List<String>
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<Long> roleIds  = UserThreadLocal.getRoleIds();
        List<String> perms = new LinkedList<>();

        if (roleIds.isEmpty()) {
            return perms;
        }

        List<SysPerm> permList = sysPermMapper.selectList(
                new QueryWrapper<SysPerm>()
                        .select("id,role_id,menu_id")
                        .in("role_id", roleIds));

        if (permList.isEmpty()) {
            return perms;
        }

        List<Long> menuIds = new LinkedList<>();
        for (SysPerm sysPerm : permList) {
            menuIds.add(sysPerm.getMenuId());
        }

        List<SysMenu> sysMenus = sysMenuMapper.selectList(
                new QueryWrapper<SysMenu>()
                        .select("id,perms")
                        .eq("is_disable", 0)
                        .in("id", menuIds)
                        .in("menu_type", Arrays.asList("C", "A"))
                        .orderByAsc(Arrays.asList("menu_sort", "id")));

        for (SysMenu i : sysMenus) {
            if (StringUtils.isNotNull(i.getPerms()) && StringUtils.isNopty(i.getPerms())) {
                perms.add(i.getPerms().trim());
            }
        }

        return perms;
    }

    /**
     * 返回一个账号所拥有的角色标识集合
     *
     * @param loginId 登录ID
     * @param loginType 登录类型
     * @return List<String>
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return null;
    }

}
